//
//  YMTakePassengerViewController.swift
//  Driver
//
//  Created by lantaiyuan on 2017/10/30.
//  Copyright © 2017年 youmy. All rights reserved.
//

import UIKit

class YMTakePassengerViewController: UIViewController {
    
    enum TravelType{
        case Start
        case End
        case Listen
    }
    
    enum MarkerType {
        case Icon
        case View
    }
    
    var currentTravel:TravelType = .Start
    
    var markerType:MarkerType = .Icon
    
    var annotations:[YMStationAnnotation] = []
    
    typealias TravelStateCloure = (_ state: TravelType)->()
    
    var travelStateCloure:TravelStateCloure?
    
    lazy var maskView:UIView = {
        let v = UIView(frame: UIScreen.main.bounds)
        v.backgroundColor = UIColor(white: 0.3, alpha: 0.7)
        return v
    }()
    
    lazy var dialogView:YMTakePassengerDialogView = {
        let v = YMTakePassengerDialogView(frame: CGRect(x: 0, y: self.view.height - 279 - 64, width: self.view.width, height: 279))
        return v
    }()
    
    
    var mapView:MAMapView?
    
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var startOrEndBtn: UIButton!
    @IBAction func startOrEndTravelAction(_ sender: UIButton) {
        
        if currentTravel == .Start {
            currentTravel = .End
            refreshBtn(currentTravel)
            // send start travel flag to server, notify to prvious page modify status
            if travelStateCloure != nil {
                travelStateCloure!(currentTravel)
            }
        }else{
            // show dialog after request end travel data
            self.maskView.addSubview(self.dialogView)
            self.view.addSubview(self.maskView)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mapView = MAMapView(frame: mainView.bounds)
        mapView?.zoomLevel = 16
        mapView?.delegate = self
        mainView.addSubview(mapView!)
        
        refreshBtn(currentTravel)
        
        self.dialogView.cancel = {[weak self] (isCancel) in
            if isCancel {
                self?.maskView.removeAllSubviews()
                self?.maskView.removeFromSuperview()
            }else{
                // end travel back to previous page, notify to prvious page modify status
                self?.currentTravel = .Listen
                if self?.travelStateCloure != nil {
                    self?.travelStateCloure!((self?.currentTravel)!)
                }
                self?.navigationController?.popViewController(animated: true)
            }
        }
        
        readData()
    }
    
    fileprivate func refreshBtn(_ type: TravelType){
        startOrEndBtn.setTitle(type == .Start ? "开始行程":"结束行程", for: .normal)
    }

}

extension YMTakePassengerViewController {
    fileprivate func readData(){
        let path = Bundle.main.path(forResource: "order.json", ofType: nil) ?? ""
        guard let data = try? Data.init(contentsOf: URL(fileURLWithPath: path)),
            let dic = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any] else {
                return
        }
        
        let order = Order_root.model(with: dic) ?? Order_root()
        let carpoolRoute = order.obj?.carpoolRoute ?? Order_carpoolRoute()
        for obj in carpoolRoute.carpoolRouteStations! {
            print(obj.stationName ?? "")
        }
        
        let latLngs = lines(order.obj?.pathLine ?? "")
        print(latLngs.count)
        drawLine(latLngs)
        
        addMarkers(order.obj?.carpoolRoute?.carpoolRouteStations ?? [])
    }
    
    fileprivate func addMarkers(_ stations: [Order_carpoolRouteStations]){
        
        if annotations.count == 0 {
            for station in stations {
                let annotation = YMStationAnnotation()
                annotation.station = station
                annotation.coordinate = CLLocationCoordinate2DMake(station.stationLat, station.stationLon)
                annotations.append(annotation)
            }
        }
        mapView?.addAnnotations(annotations)
        mapView?.showAnnotations(annotations, animated: false)
    }
    
    /// draw line on mapview
    ///
    /// - Parameter lines: line's coordinate array
    fileprivate func drawLine(_ lines: [YMLatLng]){
        
        var linePoints = [CLLocationCoordinate2D]()
        
        var i:Int64 = 0
        for obj in lines {
            let coordinate = CLLocationCoordinate2D(latitude: obj.lat, longitude: obj.lng)
            linePoints.append(coordinate)
            i = i+1
            if i == 1 {
                mapView?.setCenter(coordinate, animated: false)
            }
        }
        let polyLine = MAPolyline.init(coordinates: &linePoints, count: UInt(linePoints.count))
        mapView?.add(polyLine)
    }
}

// MARK: - MAMapViewDelegate
extension YMTakePassengerViewController: MAMapViewDelegate {
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        
        if overlay is MAPolyline {
            let polyLineRenderer = MAPolylineRenderer.init(overlay: overlay)
            polyLineRenderer?.lineWidth = 5.0
            polyLineRenderer?.loadStrokeTextureImage(UIImage(named: "arrowTexture"))
            return polyLineRenderer
        }
        
        return nil
    }
    
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        if annotation is YMStationAnnotation {
            let reuseIndentifier = "staInfoReuseIndetifier"
            if markerType == .Icon {
                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIndentifier) as? YMStationAnnotationView
                
                if annotationView == nil {
                    annotationView = YMStationAnnotationView(annotation: annotation, reuseIdentifier: reuseIndentifier)
                }
                return annotationView
                
            }else{
                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIndentifier) as? YMStationAnnotationIconView
                
                if annotationView == nil {
                    annotationView = YMStationAnnotationIconView(annotation: annotation, reuseIdentifier: reuseIndentifier)
                }
                let anno = annotation as! YMStationAnnotation
                annotationView?.station = anno
                
                return annotationView
            }
        }else if annotation is MAPointAnnotation {
            let reuseIndetifier = "myReuseIndetifier"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIndetifier)
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: reuseIndetifier)
                annotationView?.image = UIImage.init(named: "icon_car")
            }
            return annotationView
        }
        
        return nil
    }
    
    func mapView(_ mapView: MAMapView!, regionDidChangeAnimated animated: Bool) {
        print("------ \(mapView.zoomLevel)")
        
        
        if mapView.zoomLevel > 15 && markerType != .View{
            markerType = .View
            mapView.removeAnnotations(annotations)
            mapView.addAnnotations(annotations)
            
            print("--------View")
        }
        
        if mapView.zoomLevel < 15 && markerType != .Icon {
            markerType = .Icon
            mapView.removeAnnotations(annotations)
            mapView.addAnnotations(annotations)
            
            print("--------Icon")
        }
    }
}
